package com.sunricher.telinkblemesh.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sunricher.telinkblemesh.R;
import com.sunricher.telinkblemeshlib.models.UartDaliDevice;

import java.util.ArrayList;
import java.util.List;

public class DaliDevicesAdapter extends RecyclerView.Adapter<DaliDevicesAdapter.ViewHolder> {

    private List<UartDaliDevice> devices;
    private DaliDevicesAdapter.OnClickListener clickListener;

    public DaliDevicesAdapter() {
        super();
        this.devices = new ArrayList<>();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_item, parent, false);
        ViewHolder vh = new ViewHolder(view);
        view.setOnClickListener((v) -> {
            int position = vh.getAdapterPosition();
            if (clickListener != null) {
                clickListener.onItemClick(vh, position, devices.get(position));
            }
        });
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        UartDaliDevice device = devices.get(position);
        String name = device.getCommonName();
        holder.getTextLabel().setText(name);
    }

    @Override
    public int getItemCount() {
        return devices.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private final TextView textLabel;

        public ViewHolder(View view) {
            super(view);
            textLabel = (TextView) view.findViewById(R.id.text_label);
        }

        public TextView getTextLabel() {
            return textLabel;
        }
    }

    public void updateDevices(List<UartDaliDevice> devices) {
        this.devices = devices;
        this.notifyDataSetChanged();
    }

    public interface OnClickListener {
        void onItemClick(ViewHolder holder, int position, UartDaliDevice device);
    }

    public void setClickListener(OnClickListener clickListener) {
        this.clickListener = clickListener;
    }

    public List<UartDaliDevice> getDevices() {
        return devices;
    }
}
